package cn.com.css.taxInspection.xtgl.controller;

import cn.com.css.taxInspection.common.aop.annotation.LogAnnotation;
import cn.com.css.taxInspection.common.result.DataResult;
import cn.com.css.taxInspection.util.TsBqUtils;
import cn.com.css.taxInspection.xtgl.entity.ZbcxEntity;
import cn.com.css.taxInspection.xtgl.service.SysZbcxService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Connection;
import java.util.*;

/**
 * 系统管理-指标查询
 */
@RequestMapping("/zbcx")
@RestController
@Api(tags = "指标查询")
public class ZbcxController {

    @Resource
    private SysZbcxService sysZbcxService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @PostMapping("/queryZbcx")
    @ApiOperation(value = "指标查询")
    @LogAnnotation(title = "指标查询", action = "指标查询")
    public DataResult queryGzcbData(@RequestBody ZbcxEntity zbcxEntity) throws Exception {
        String tableCode = TsBqUtils.isNull(zbcxEntity.getCode()) ? "1" : zbcxEntity.getCode();

        ZbcxEntity newZbcxEntity = sysZbcxService.queryZbcxData(zbcxEntity);
        if (TsBqUtils.isNull(newZbcxEntity)) {
            return DataResult.fail("未找到指标查询对应表配置: " + tableCode);
        }

        String rawSql = newZbcxEntity.getQuerySql().trim();

        int page  = zbcxEntity.getPage()  > 0 ? zbcxEntity.getPage()  : 1;
        int limit = zbcxEntity.getLimit() > 0 ? zbcxEntity.getLimit() : 10;
        int offset = (page - 1) * limit;

        // 统一的总数 SQL
        String countSql = "SELECT COUNT(1) FROM (" + rawSql + ") t";

        // —— 关键：统一包一层再分页，按方言拼接 —— //
        String dbName;
        try (Connection c = Objects.requireNonNull(jdbcTemplate.getDataSource()).getConnection()) {
            dbName = c.getMetaData().getDatabaseProductName(); // "MySQL" / "PostgreSQL" / "Oracle" ...
        }

        String pagedSql;
        Object[] args;
        if (dbName.toLowerCase().contains("postgres")) {
            // PostgreSQL
            pagedSql = "SELECT * FROM (" + rawSql + ") t LIMIT ? OFFSET ?";
            args = new Object[]{limit, offset};
        } else if (dbName.toLowerCase().contains("mysql")) {
            // MySQL（兼容 5.7）：LIMIT offset, limit
            pagedSql = "SELECT * FROM (" + rawSql + ") t LIMIT ?, ?";
            args = new Object[]{offset, limit};
        } else if (dbName.toLowerCase().contains("oracle")) {
            // Oracle（12c+可用 OFFSET/FETCH；以下写法两边都兼容）
            pagedSql = "SELECT * FROM ( SELECT t.*, ROWNUM rn FROM (" + rawSql + ") t WHERE ROWNUM <= ? ) WHERE rn > ?";
            args = new Object[]{offset + limit, offset};
        } else {
            // 兜底按 PostgreSQL 处理
            pagedSql = "SELECT * FROM (" + rawSql + ") t LIMIT ? OFFSET ?";
            args = new Object[]{limit, offset};
        }

        // 执行
        List<Map<String, Object>> list = jdbcTemplate.queryForList(pagedSql, args);
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class);
        if (total == null) total = 0;

        // 返回给前端（保持你现在的结构，前端 parseData 已经适配）
        Map<String, Object> body = new HashMap<>();
        body.put("count", total);
        body.put("data", list);
        body.put("columnsJson", newZbcxEntity.getColumnsJson());

        // 统一包一层 DataResult
        return DataResult.success(body);
    }



    @ApiOperation(value = "指标查询-查询指标")
    @LogAnnotation(title = "立案检查人员调整", action = "查询指标")
    @PostMapping("/queryZbcxSelect")
    @ResponseBody
    public DataResult queryZbcxSelect() {
        // 按 code 升序查询
        QueryWrapper<ZbcxEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("code"); // 按字段 code 升序
        List<ZbcxEntity> zbcxEntityList = sysZbcxService.list(queryWrapper);
        return DataResult.success(zbcxEntityList);
    }

}